import Vue from "vue";
import VueRouter, {RouteConfig} from "vue-router";
import Login from "@/views/Login.vue";
import Item from "@/components/Item.vue";
import Detail from "@/components/Detail.vue";
import NotFound from "@/components/NotFound.vue";
import Nav from "@/components/Nav.vue";
import My from "@/components/My.vue";
import store from "../store/index";
import {message} from "ant-design-vue";
import {Toast} from "vant";

Vue.use(VueRouter);

const routes: Array<RouteConfig> = [
  {
    path: "/",
    redirect: "/nav"
  },
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/item",
    component: Item,
    meta: {requireAuth: true}
  },
  {
    path: "/detail",
    component: Detail,
    meta: {requireAuth: true}
  },
  {
    path: "/nav",
    component: Nav,
    meta: {requireAuth: true}
  },
  {
    path: "/my",
    component: My,
    meta: {requireAuth: true}
  },
  {
    path: "*",
    component: NotFound
  }
];

const router = new VueRouter({
  routes
});
router.beforeEach((to, from, next) => {
  store.commit("getUser");
  if (to.matched.some(record => record.meta.requireAuth)) {
    if (!store.state.user) {
      Toast.fail({message: "用户未登录，即将跳转至登录页面", duration: 2000});
      setTimeout(() => {
        next({
          path: "/login",
          // query: {redirect: to.fullPath}
        });
      }, 2200);
    } else {
      next();
    }
  } else {
    if (!store.state.user) {
      next();
    } else {
      next(false);
    }
    // next(); // 确保一定要调用 next()
  }
});
const originalPush = VueRouter.prototype.push;


export default router;
